<script setup name="TenantPackage" lang="ts">
import { Modal, TreeSelect } from 'ant-design-vue'
import {
  addTenantPackage,
  changePackageStatus,
  delTenantPackage,
  getTenantPackage,
  listTenantPackage,
  updateTenantPackage,
} from '@/api/system/tenantPackage'
import { treeselect as menuTreeselect, tenantPackageMenuTreeselect } from '@/api/system/menu'
import type { TenantPkgForm, TenantPkgQuery, TenantPkgVO } from '@/api/system/tenantPackage/types'
import type { MenuTreeOption } from '@/api/system/menu/types'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const tenantPackageList = ref<TenantPkgVO[]>([])
const buttonLoading = ref(false)
const loading = ref(true)

const ids = ref<Array<string | number>>([])
const total = ref(0)
const message = useMessage()
const modal = useModal()
const menuExpand = ref(false)
const menuNodeAll = ref(false)
const menuOptions = ref<MenuTreeOption[]>([])
const SHOW_PARENT = TreeSelect.SHOW_ALL
const menuTreeRef = ref()
const queryFormRef = ref()
const tenantPackageFormRef = ref()

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

const initFormData: TenantPkgForm = {
  packageId: undefined,
  packageName: '',
  menuIds: '',
  remark: '',
  menuCheckStrictly: true,
}
const data = reactive<PageData<TenantPkgForm, TenantPkgQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    packageName: '',
  },
  rules: {
    packageId: [{ required: true, message: '租户套餐id不能为空', trigger: 'blur' }],
    packageName: [{ required: true, message: '套餐名称不能为空', trigger: 'blur' }],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询菜单树结构 */
async function getMenuTreeselect() {
  const { data } = await menuTreeselect()
  menuOptions.value = data
}

/** 根据租户套餐ID查询菜单树结构 */
async function getPackageMenuTreeselect(packageId: string | number) {
  const res = await tenantPackageMenuTreeselect(packageId)
  menuOptions.value = res.data.menus
  return Promise.resolve(res)
}

/** 查询租户套餐列表 */
async function getList() {
  loading.value = true
  const res = await listTenantPackage(queryParams.value)
  tenantPackageList.value = res.rows
  total.value = res.total
  loading.value = false
}

// 租户套餐状态修改
async function handleStatusChange(row: TenantPkgVO) {
  const text = row.status === '0' ? '启用' : '停用'
  Modal.confirm({
    title: '修改状态',
    content: `确认要"${text}""${row.packageName}"套餐吗？`,
    cancelText: '取消',
    okText: '确认',
    onOk: async () => {
      await changePackageStatus(row.packageId, row.status)
      message.success(`${text}成功`)
    },
    onCancel() {
      row.status = row.status === '0' ? '1' : '0'
    },
  })
}

// 取消按钮
function cancel() {
  reset()
  dialog.visible = false
}

// 表单重置
function reset() {
  menuTreeRef.value?.setCheckedKeys([])
  menuExpand.value = false
  menuNodeAll.value = false
  form.value = { ...initFormData }
  tenantPackageFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getMenuTreeselect()
  dialog.visible = true
  dialog.title = '添加租户套餐'
}

/** 修改按钮操作 */
async function handleUpdate(row?: TenantPkgVO) {
  reset()
  const _packageId = row?.packageId || ids.value[0]
  const response = await getTenantPackage(_packageId)
  form.value = response.data
  const res = await getPackageMenuTreeselect(_packageId)
  dialog.visible = true
  dialog.title = '修改租户套餐'
  form.value.menuIds = res.data.checkedKeys
}

/** 提交按钮 */
function submitForm() {
  tenantPackageFormRef.value?.validate().then(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true
      if (form.value.packageId != null)
        await updateTenantPackage(form.value).finally(() => buttonLoading.value = false)
      else
        await addTenantPackage(form.value).finally(() => buttonLoading.value = false)

      message.success('操作成功')
      dialog.visible = false
      await getList()
    }
  })
}

/** 删除按钮操作 */
async function handleDelete(row?: TenantPkgVO) {
  const _packageIds = row?.packageId || ids.value
  modal.confirm({
    title: '确认删除',
    content: `是否确认删除租户套餐编号为"${row?.packageName}"的数据项?`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await delTenantPackage(_packageIds)
      await getList()
      message.success('删除成功')
    },
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('system/tenantPackage/export', {
    ...queryParams.value,
  }, `tenantPackage_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="p-2">
    <a-card class="mb-20px">
      <div class="flex flex-between">
        <div>
          <a-form ref="queryFormRef" :model="queryParams" layout="inline">
            <a-form-item label="套餐名称" prop="packageName">
              <a-input
                v-model:value="queryParams.packageName" placeholder="请输入套餐名称" clearable style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="handleQuery">
                  搜索
                </a-button>
                <a-button @click="resetQuery">
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <a-row :gutter="10" class="mb8">
            <a-col :span="1.5">
              <a-button v-hasPermi="['system:tenantPackage:add']" type="primary" @click="handleAdd">
                新增
              </a-button>
            </a-col>

            <a-col :span="1.5">
              <a-button v-hasPermi="['system:tenantPackage:export']" @click="handleExport">
                导出
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-card>

    <a-card shadow="hover">
      <a-table :data-source="tenantPackageList" :pagination="false">
        <a-table-column title="套餐名称" align="left" data-index="packageName" />
        <a-table-column title="备注" align="center" data-index="remark" />
        <a-table-column title="状态" align="center" data-index="status">
          <template #default="{ record }">
            <a-switch
              v-model:checked="record.status"
              checked-value="0" un-checked-value="1"
              @click="handleStatusChange(record)"
            />
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center">
          <template #default="{ record }">
            <a-tooltip content="修改" placement="top">
              <a-button
                v-hasPermi="['system:tenantPackage:edit']" link type="link"
                @click="handleUpdate(record)"
              >
                修改
              </a-button>
            </a-tooltip>
            <a-tooltip content="删除" placement="top">
              <a-button
                v-hasPermi="['system:tenantPackage:remove']" link type="link"
                @click="handleDelete(record)"
              >
                删除
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>

      <div class="text-right mt-20px">
        <a-pagination
          v-show="total > 0"
          v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" :total="total"
          show-less-items @change="getList"
        />
      </div>
    </a-card>

    <!-- 添加或修改租户套餐对话框 -->
    <a-modal v-model:open="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <a-form ref="tenantPackageFormRef" :model="form" :rules="rules" laba-width="80px">
        <a-form-item label="套餐名称" name="packageName">
          <a-input v-model:value="form.packageName" placeholder="请输入套餐名称" />
        </a-form-item>
        <a-form-item label="关联菜单">
          <a-tree-select
            v-model:value="form.menuIds"
            class="tree-border"
            :tree-data="menuOptions"
            tree-checkable
            allow-clear
            :tree-default-expand-all="true"
            :show-checked-strategy="SHOW_PARENT"
            tree-node-filter-prop="label"
            :field-names="{ label: 'label', value: 'id', children: 'children' }"
          />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-input v-model:value="form.remark" placeholder="请输入备注" />
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button :loading="buttonLoading" type="primary" @click="submitForm">
            确 定
          </a-button>
          <a-button @click="cancel">
            取 消
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
